package org.ccams.util;

import java.io.IOException;
import java.security.MessageDigest;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @name Utils
 * @title 实用工具类
 * @description
 * @author liuguangshuai@gmail.com
 * @date 2007-10-24
 */
public class Utils {
	private static Log log;
    public static final String TIMESTAMPFORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String TIMEFORMAT = "HH:mm:ss";
    public static final String DATEFORMAT = "yyyy-MM-dd";
    public static final String DATETIMEFORMAT = "yyyy-MM-dd hh:mm:ss";
	
	/**
	 * @name areTheyEquals
	 * @title 判断两个对象是否相等
	 * @param Object,
	 *            Object
	 * @return boolean
	 * @description 使用此方法能够回避空对象调用.equals()方法出错的问题哦!
	 */
	public static boolean areTheyEquals(Object obj1, Object obj2) {
		if (obj1 == null) {
			return obj2 == null;
		} else {
			return obj1.equals(obj2);
		}
	}

	/*
	 * 根据当前时间获得17位数字组成的字符串，用于id
	 */
	public static String getID() {
		SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyyMMddHmsSSS");
		return (String) bartDateFormat.format(new Date());
	}
	
	/**
	 * @name areTheyEqualsIgnoreCase
	 * @title 判断两个字符串对象是否相等(忽略大小写)
	 * @param String,
	 *            String
	 * @return boolean
	 * @description 使用此方法能够回避空对象调用.equals()方法出错的问题哦!
	 */
	public static boolean areTheyEqualsIgnoreCase(String str1, String str2) {
		if (str1 == null) {
			return str2 == null;
		} else {
			return str1.equalsIgnoreCase(str2);
		}
	}

	/**
	 * @name isEmpty
	 * @title 判断对象是否Empty(null或元素为0)
	 * @param Object
	 * @return boolean
	 * @description 实用于对如下对象做判断:String Collection及其子类 Map及其子类
	 */
	public static boolean isEmpty(Object value) {
		if (value == null)
			return true;
		if (value instanceof String) {
			if (((String) value).length() == 0) {
				return true;
			}
		} else if (value instanceof Collection) {
			if (((Collection) value).size() == 0) {
				return true;
			}
		} else if (value instanceof Map) {
			if (((Map) value).size() == 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @name isNotEmpty
	 * @title 判断对象是否为NotEmpty(!null或元素>0)
	 * @param Object
	 * @return boolean
	 * @description 实用于对如下对象做判断:String Collection及其子类 Map及其子类
	 */
	public static boolean isNotEmpty(Object value) {
		if (value == null)
			return false;
		if (value instanceof String) {
			if (((String) value).length() == 0) {
				return false;
			}
		} else if (value instanceof Collection) {
			if (((Collection) value).size() == 0) {
				return false;
			}
		} else if (value instanceof Map) {
			if (((Map) value).size() == 0) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * @name removeCharsInStrBag
	 * @title 移除在字符串bag中所有和字符串s中的字符匹配的字符
	 * @param String,
	 *            String
	 * @return String
	 * @description
	 */
	public static String removeCharsInStrBag(String s, String bag) {
		int i;
		String returnString = "";
		for (i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (bag.indexOf(c) == -1)
				returnString += c;
		}
		return returnString;
	}

	/**
	 * @name removeCharsNotInStrBag
	 * @title 移除在字符串bag中所有没和字符串s中的字符匹配的字符
	 * @param String,
	 *            String
	 * @return String
	 * @description
	 */
	public static String removeCharsNotInStrBag(String s, String bag) {
		int i;
		String returnString = "";
		for (i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (bag.indexOf(c) != -1)
				returnString += c;
		}
		return returnString;
	}

	/**
	 * @name charInString
	 * @title 判断一个字符是否再给定的字符串中
	 * @param char,
	 *            String
	 * @return boolean
	 * @description
	 */
	public static boolean charInString(char c, String s) {
		return (s.indexOf(c) != -1);
	}

	/**
	 * @name isLetter
	 * @title 判断一个字符是否是否为英文字符
	 * @param char
	 * @return boolean
	 * @description A-Z, a-z
	 */
	public static boolean isLetter(char c) {
		return Character.isLetter(c);
	}
	
	/**
	 * @name isUrl
	 * @title 判断一个字符串是否为URL格式的字符串
	 * @param String
	 * @return boolean
	 * @description 0-9
	 */
	public static boolean isUrl(String s) {
		if (s.indexOf("://") != -1)
			return true;
		return false;
	}
	
    public static boolean startsWithIgnoreCase(String str, String prefix)
    {
        if(str == null || prefix == null)
            return false;
        if(str.startsWith(prefix))
            return true;
        if(str.length() < prefix.length())
        {
            return false;
        } else
        {
            String lcStr = str.substring(0, prefix.length()).toLowerCase();
            String lcPrefix = prefix.toLowerCase();
            return lcStr.equals(lcPrefix);
        }
    }

    public static int countOccurrencesOf(String str, String sub)
    {
        if(str == null || sub == null || str.length() == 0 || sub.length() == 0)
            return 0;
        int count = 0;
        int pos = 0;
        for(int idx = 0; (idx = str.indexOf(sub, pos)) != -1;)
        {
            count++;
            pos = idx + sub.length();
        }

        return count;
    }

    public static String delete(String inString, String pattern)
    {
        return StringUtils.replace(inString, pattern, "");
    }

    public static String deleteAny(String inString, String charsToDelete)
    {
        if(inString == null || charsToDelete == null)
            return inString;
        StringBuffer out = new StringBuffer();
        for(int i = 0; i < inString.length(); i++)
        {
            char c = inString.charAt(i);
            if(charsToDelete.indexOf(c) == -1)
                out.append(c);
        }

        return out.toString();
    }

    public static String unqualify(String qualifiedName)
    {
        return unqualify(qualifiedName, '.');
    }

    public static String unqualify(String qualifiedName, char separator)
    {
        return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);
    }

    public static String getFilename(String path)
    {
        int separatorIndex = path.lastIndexOf("/");
        return separatorIndex == -1 ? path : path.substring(separatorIndex + 1);
    }
    /**
     * 路径处理
     * @name 
     * @param 
     * @return String
     * @description
     */
    public static String applyRelativePath(String path, String relativePath)
    {
        int separatorIndex = path.lastIndexOf("/");
        if(separatorIndex != -1)
        {
            String newPath = path.substring(0, separatorIndex);
            if(!relativePath.startsWith("/"))
                newPath = newPath + "/";
            return newPath + relativePath;
        } else
        {
            return relativePath;
        }
    }

    public static String cleanPath(String path)
    {
        String pathToUse = StringUtils.replace(path, "\\", "/");
        String pathArray[] = delimitedListToStringArray(pathToUse, "/");
        List pathElements = new LinkedList();
        int tops = 0;
        for(int i = pathArray.length - 1; i >= 0; i--)
            if(!".".equals(pathArray[i]))
                if("..".equals(pathArray[i]))
                    tops++;
                else
                if(tops > 0)
                    tops--;
                else
                    pathElements.add(0, pathArray[i]);

        return collectionToDelimitedString(pathElements, "/");
    }

    public static boolean pathEquals(String path1, String path2)
    {
        return cleanPath(path1).equals(cleanPath(path2));
    }

    public static Locale parseLocaleString(String localeString)
    {
        String parts[] = tokenizeToStringArray(localeString, "_ ", false, false);
        String language = parts.length <= 0 ? "" : parts[0];
        String country = parts.length <= 1 ? "" : parts[1];
        String variant = parts.length <= 2 ? "" : parts[2];
        return language.length() <= 0 ? null : new Locale(language, country, variant);
    }

    public static String[] addStringToArray(String arr[], String str)
    {
        String newArr[] = new String[arr.length + 1];
        System.arraycopy(arr, 0, newArr, 0, arr.length);
        newArr[arr.length] = str;
        return newArr;
    }

    public static String[] sortStringArray(String source[])
    {
        if(source == null)
        {
            return new String[0];
        } else
        {
            Arrays.sort(source);
            return source;
        }
    }

    public static Properties splitArrayElementsIntoProperties(String array[], String delimiter)
    {
        return splitArrayElementsIntoProperties(array, delimiter, null);
    }

    public static Properties splitArrayElementsIntoProperties(String array[], String delimiter, String charsToDelete)
    {
        if(array == null || array.length == 0)
            return null;
        Properties result = new Properties();
        for(int i = 0; i < array.length; i++)
        {
            String element = array[i];
            if(charsToDelete != null)
                element = deleteAny(array[i], charsToDelete);
            String splittedElement[] = StringUtils.split(element, delimiter);
            if(splittedElement != null)
                result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());
        }

        return result;
    }

    public static String[] tokenizeToStringArray(String str, String delimiters)
    {
        return tokenizeToStringArray(str, delimiters, true, true);
    }
    /**
     * 
     * @name 
     * @param 
     * @return String[]
     * @description
     */
    public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens)
    {
        StringTokenizer st = new StringTokenizer(str, delimiters);
        List tokens = new ArrayList();
        while(st.hasMoreTokens()) 
        {
            String token = st.nextToken();
            if(trimTokens)
                token = token.trim();
            if(!ignoreEmptyTokens || token.length() > 0)
                tokens.add(token);
        }
        return (String[])tokens.toArray(new String[tokens.size()]);
    }
    /**
     * 将str转换成数组
     * @name 
     * @param 
     * @return String[]
     * @description
     */
    public static String[] delimitedListToStringArray(String str, String delimiter)
    {
        if(str == null)
            return new String[0];
        if(delimiter == null)
            return (new String[] {
                str
            });
        List result = new ArrayList();
        int pos = 0;
        for(int delPos = 0; (delPos = str.indexOf(delimiter, pos)) != -1;)
        {
            result.add(str.substring(pos, delPos));
            pos = delPos + delimiter.length();
        }

        if(str.length() > 0 && pos <= str.length())
            result.add(str.substring(pos));
        return (String[])result.toArray(new String[result.size()]);
    }

    public static String[] commaDelimitedListToStringArray(String str)
    {
        return delimitedListToStringArray(str, ",");
    }

    public static Set commaDelimitedListToSet(String str)
    {
        Set set = new TreeSet();
        String tokens[] = commaDelimitedListToStringArray(str);
        for(int i = 0; i < tokens.length; i++)
            set.add(tokens[i]);

        return set;
    }

    public static String arrayToDelimitedString(Object arr[], String delim)
    {
        if(arr == null)
            return "";
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < arr.length; i++)
        {
            if(i > 0)
                sb.append(delim);
            sb.append(arr[i]);
        }

        return sb.toString();
    }

    public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix)
    {
        if(coll == null)
            return "";
        StringBuffer sb = new StringBuffer();
        Iterator it = coll.iterator();
        for(int i = 0; it.hasNext(); i++)
        {
            if(i > 0)
                sb.append(delim);
            sb.append(prefix).append(it.next()).append(suffix);
        }

        return sb.toString();
    }

    public static String collectionToDelimitedString(Collection coll, String delim)
    {
        return collectionToDelimitedString(coll, delim, "", "");
    }

    public static String arrayToCommaDelimitedString(Object arr[])
    {
        return arrayToDelimitedString(arr, ",");
    }

    public static String collectionToCommaDelimitedString(Collection coll)
    {
        return collectionToDelimitedString(coll, ",");
    }
    /**
     * 加密密码
     * @name 
     * @param 
     * @return String
     * @description
     */
    public static String encodePassword(String password, String algorithm)
    {
        byte unencodedPassword[] = password.getBytes();
        MessageDigest md = null;
        try
        {
            md = MessageDigest.getInstance(algorithm);
        }
        catch(Exception e)
        {
            log.error("Exception: " + e);
            return password;
        }
        md.reset();
        md.update(unencodedPassword);
        byte encodedPassword[] = md.digest();
        StringBuffer buf = new StringBuffer();
        for(int i = 0; i < encodedPassword.length; i++)
        {
            if((encodedPassword[i] & 0xff) < 16)
                buf.append("0");
            buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }

        return buf.toString();
    }
    /**
     * 加密字符串
     * @name 
     * @param 
     * @return String
     * @description
     */
    public static String encodeString(String str)
    {
        BASE64Encoder encoder = new BASE64Encoder();
        return (new String(encoder.encodeBuffer(str.getBytes()))).trim();
    }
    /**
     * 解密字符串
     * @name 
     * @param 
     * @return String
     * @description
     */
    public static String decodeString(String str)
    {
        BASE64Decoder dec = new BASE64Decoder();
        try
        {
            return new String(dec.decodeBuffer(str));
        }
        catch(IOException io)
        {
            throw new RuntimeException(io.getMessage(), io.getCause());
        }
    }

    public static String toChinese(String strvalue)
    {
        try
        {
            if(strvalue == null)
            {
                return null;
            } else
            {
                strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK");
                return strvalue;
            }
        }
        catch(Exception e)
        {
            return null;
        }
    }
    
	/**
	 * @name isLetter
	 * @title 判断一个字符是否是否为数字
	 * @param char
	 * @return boolean
	 * @description 0-9
	 */
	public static boolean isDigit(char c) {
		return Character.isDigit(c);
	}

	/**
	 * @name isLetter
	 * @title 判断一个字符是否是否为数字或字符
	 * @param char
	 * @return boolean
	 * @description 0-9, a-z, A-Z
	 */
	public static boolean isLetterOrDigit(char c) {
		return Character.isLetterOrDigit(c);
	}

	/**
	 * @name isNumberString
	 * @title 判断一个字符串是否由数字字符组成
	 * @param String
	 * @return boolean
	 * @description 0-9
	 */
	public static boolean isNumberString(String s) {
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (!isDigit(c))
				return false;
		}
		return true;
	}
	

	static String HanDigiStr[] = new String[] { "零", "壹", "贰", "叁", "肆", "伍",
			"陆", "柒", "捌", "玖" };

	static String HanDiviStr[] = new String[] { "", "拾", "佰", "仟", "万", "拾",
			"佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰",
			"仟", "万", "拾", "佰", "仟" };

	public static String PositiveIntegerToHanStr(String NumStr) { // 输入字符串必须正整数，只允许前导空格(必须右对齐)，不宜有前导零
		String RMBStr = "";
		boolean lastzero = false;
		boolean hasvalue = false; // 亿、万进位前有数值标记
		int len, n;
		len = NumStr.length();
		if (len > 15)
			return "数值过大!";
		for (int i = len - 1; i >= 0; i--) {
			if (NumStr.charAt(len - i - 1) == ' ')
				continue;
			n = NumStr.charAt(len - i - 1) - '0';
			if (n < 0 || n > 9)
				return "输入含非数字字符!";

			if (n != 0) {
				if (lastzero)
					RMBStr += HanDigiStr[0]; // 若干零后若跟非零值，只显示一个零
				// 除了亿万前的零不带到后面
				// if( !( n==1 && (i%4)==1 && (lastzero || i==len-1) ) ) //
				// 如十进位前有零也不发壹音用此行
				if (!(n == 1 && (i % 4) == 1 && i == len - 1)) // 十进位处于第一位不发壹音
					RMBStr += HanDigiStr[n];
				RMBStr += HanDiviStr[i]; // 非零值后加进位，个位为空
				hasvalue = true; // 置万进位前有值标记

			} else {
				if ((i % 8) == 0 || ((i % 8) == 4 && hasvalue)) // 亿万之间必须有非零值方显示万
					RMBStr += HanDiviStr[i]; // “亿”或“万”
			}
			if (i % 8 == 0)
				hasvalue = false; // 万进位前有值标记逢亿复位
			lastzero = (n == 0) && (i % 4 != 0);
		}

		if (RMBStr.length() == 0)
			return HanDigiStr[0]; // 输入空字符或"0"，返回"零"
		return RMBStr;
	}
	/**
	 * @name 
	 * @title 将货币转换为大写形式
	 * @param String
	 * @return String
	 * @description   
	 */
	public static String NumToRMBStr(double val) {
		String SignStr = "";
		String TailStr = "";
		long fraction, integer;
		int jiao, fen;

		if (val < 0) {
			val = -val;
			SignStr = "负";
		}
		if (val > 99999999999999.999 || val < -99999999999999.999)
			return "数值位数过大!";
		// 四舍五入到分
		long temp = Math.round(val * 100);
		integer = temp / 100;
		fraction = temp % 100;
		jiao = (int) fraction / 10;
		fen = (int) fraction % 10;
		if (jiao == 0 && fen == 0) {
			TailStr = "整";
		} else {
			TailStr = HanDigiStr[jiao];
			if (jiao != 0)
				TailStr += "角";
			// 零元后不写零几分
			if (integer == 0 && jiao == 0)
				TailStr = "";
			if (fen != 0)
				TailStr += HanDigiStr[fen] + "分";
		}
		// 下一行可用于非正规金融场合，0.03只显示“叁分”而不是“零元叁分”
		// if( !integer ) return SignStr+TailStr;
		return SignStr + PositiveIntegerToHanStr(String.valueOf(integer)) + "元"
				+ TailStr;
	}
	
	/**
	 * @name string2SqlTimestamp
	 * @title 将字符串转换为Timestamp
	 * @param int
	 * @return int
	 * @description
	 */
    public static Timestamp string2SqlTimestamp(String strDate){
    	return Timestamp.valueOf(strDate + " 00:00:00");
    }
    
    /**
	 * @name string2SqlTimestamp
	 * @title 将字符串转换为Timestamp
	 * @param int
	 * @return int
	 * @description
	 */
    public static Timestamp stringTSqlTimestamp(String strDate){
    	return Timestamp.valueOf(strDate);
    }
    
	/**
	 * @name daysInFebruary
	 * @title 计算指定年份的瑞月天数
	 * @param int
	 * @return int
	 * @description
	 */
	public static int daysInFebruary(int year) {
		return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29
				: 28);
	}

	/**
	 * @name getDaysInMonth
	 * @title 获取指定年份和月份对应的天数
	 * @param int
	 *            指定的年份,指定的月份
	 * @return int
	 * @description
	 */
	public static int getDaysInMonth(int year, int month) {

		if ((month == 1) || (month == 3) || (month == 5) || (month == 7)
				|| (month == 8) || (month == 10) || (month == 12)) {

			return 31;
		} else if ((month == 4) || (month == 6) || (month == 9)
				|| (month == 11)) {

			return 30;
		} else {
			if (((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0)) {

				return 29;
			} else {
				return 28;
			}
		}
	}

	/**
	 * @name getIntervalDays
	 * @title 根据所给的起止时间来计算间隔的天数
	 * @param Date
	 *            起始时间, Date 结束时间
	 * @return int
	 * @description
	 */
	public static int getIntervalDays(java.sql.Date startDate,
			java.sql.Date endDate) {
		long startdate = startDate.getTime();
		long enddate = endDate.getTime();
		long interval = enddate - startdate;
		int intervalday = (int) (interval / (1000 * 60 * 60 * 24));
		return intervalday;
	}

	/**
	 * @name getIntervalMonths
	 * @title 根据所给的起止时间来计算间隔的月数
	 * @param Date
	 *            起始时间, Date 结束时间
	 * @return int
	 * @description
	 */
	public static int getIntervalMonths(java.sql.Date startDate,
			java.sql.Date endDate) {
		int startdatem = startDate.getMonth();
		int startdatey = startDate.getYear();
		int enddatem = endDate.getMonth();
		int enddatey = endDate.getYear();
		int interval = (enddatey * 12 + enddatem)
				- (startdatey * 12 + startdatem);
		return interval;
	}

	/**
	 * @name getIntervalMonths
	 * @title 根据所给的起止时间字符串来计算间隔的月数
	 * @param String
	 *            起始时间, String 结束时间(格式:YYYYMM)
	 * @return int
	 * @description 入参格式:YYYYMM
	 */
	public static int getIntervalMonths(String startDate, String endDate) {
		if (startDate.length() > 6) {
			startDate = fnGetStr4Y2M(startDate);
		}
		if (endDate.length() > 6) {
			endDate = fnGetStr4Y2M(endDate);
		}
		int startYear = Integer.parseInt(startDate.substring(0, 4));
		int startMonth = 0;
		if (startDate.substring(4, 5).equals("0")) {
			startMonth = Integer.parseInt(startDate.substring(5));
		}
		startMonth = Integer.parseInt(startDate.substring(4, 6));

		int endYear = Integer.parseInt(endDate.substring(0, 4));
		int endMonth = 0;
		if (endDate.substring(4, 5).equals("0")) {
			endMonth = Integer.parseInt(endDate.substring(5));
		}
		endMonth = Integer.parseInt(endDate.substring(4, 6));

		int intervalMonth = (endYear * 12 + endMonth)
				- (startYear * 12 + startMonth);
		return intervalMonth;
	}

	/**
	 * @name fnGetStr4Y2M
	 * @title 将日期返回yyyymm字符串格式
	 * @param String
	 * @return String
	 * @description
	 */
	public static final String fnGetStr4Y2M(String szStr) {
		String szRst = szStr;
		szRst = szRst.replaceAll("[ \\|\\-:\\.]", "");
		szRst = szRst.substring(0, 6);
		return szRst;
	}

    public static String getFullCurrentTime()
    {
        String returnStr = null;
        long currentTime = System.currentTimeMillis();
        Date date = new Date(currentTime);
        returnStr = DateFormat.getDateTimeInstance().format(date);
        return returnStr;
    }

    public static String getCurrentTime()
    {
        String returnStr = null;
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        returnStr = f.format(date);
        return returnStr;
    }

    public static String getCurrentTime(String format)
    {
        String returnStr = null;
        SimpleDateFormat f = new SimpleDateFormat(format);
        Date date = new Date();
        returnStr = f.format(date);
        return returnStr;
    }

    public static Date getCurrentDateTime()
    {
        return new Date(System.currentTimeMillis());
    }

    public static int getWeekOfYear()
    {
        Calendar oneCalendar = Calendar.getInstance();
        return oneCalendar.get(3);
    }

    public static int getMonth()
    {
        Calendar oneCalendar = Calendar.getInstance();
        return oneCalendar.get(2) + 1;
    }

    public static String getCurDateTime()
    {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = simpledateformat.format(calendar.getTime());
        return s;
    }

    public static Date getCurDate()
    {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd");
        String s = simpledateformat.format(calendar.getTime());
        return java.sql.Date.valueOf(s);
    }

    public static java.sql.Date getDate()
    {
        Calendar oneCalendar = Calendar.getInstance();
        return getDate(oneCalendar.get(1), oneCalendar.get(2) + 1, oneCalendar.get(5));
    }

    public static java.sql.Date getDate(int yyyy, int MM, int dd)
    {
        if(!verityDate(yyyy, MM, dd))
        {
            throw new IllegalArgumentException("This is illegimate date!");
        } else
        {
            Calendar oneCalendar = Calendar.getInstance();
            oneCalendar.clear();
            oneCalendar.set(yyyy, MM - 1, dd);
            return new java.sql.Date(oneCalendar.getTime().getTime());
        }
    }

    public static java.sql.Date getDate(String year, String month, String day)
    {
        int iYear = Integer.parseInt(year);
        int iMonth = Integer.parseInt(month);
        int iDay = Integer.parseInt(day);
        return getDate(iYear, iMonth, iDay);
    }

    public static Date getDate(int month, int day, int year, int hour, int minute, int second)
    {
        Calendar calendar = Calendar.getInstance();
        try
        {
            calendar.set(year, month - 1, day, hour, minute, second);
        }
        catch(Exception e)
        {
            return null;
        }
        return new Date(calendar.getTime().getTime());
    }

    public static Date getDate(String month, String day, String year, String hour, String minute, String second)
    {
        int iYear = Integer.parseInt(year);
        int iMonth = Integer.parseInt(month);
        int iDay = Integer.parseInt(day);
        int iHour = Integer.parseInt(hour);
        int iMinute = Integer.parseInt(minute);
        int iSecond = Integer.parseInt(second);
        return getDate(iMonth, iDay, iYear, iHour, iMinute, iSecond);
    }

    public static boolean verityDate(int yyyy, int MM, int dd)
    {
        boolean flag = false;
        if(MM >= 1 && MM <= 12 && dd >= 1 && dd <= 31)
            if(MM == 4 || MM == 6 || MM == 9 || MM == 11)
            {
                if(dd <= 30)
                    flag = true;
            } else
            if(MM == 2)
            {
                if(yyyy % 100 != 0 && yyyy % 4 == 0 || yyyy % 400 == 0)
                {
                    if(dd <= 29)
                        flag = true;
                } else
                if(dd <= 28)
                    flag = true;
            } else
            {
                flag = true;
            }
        return flag;
    }

    public static int getIntervalDay(java.sql.Date startDate, java.sql.Date endDate)
    {
        long startdate = startDate.getTime();
        long enddate = endDate.getTime();
        long interval = enddate - startdate;
        int intervalday = (int)(interval / 0x5265c00L);
        return intervalday;
    }

    public static int getIntervalMonth(String startDate, String endDate)
    {
        int startYear = Integer.parseInt(startDate.substring(0, 4));
        int startMonth = 0;
        if(startDate.substring(4, 5).equals("0"))
            startMonth = Integer.parseInt(startDate.substring(5));
        startMonth = Integer.parseInt(startDate.substring(4, 6));
        int endYear = Integer.parseInt(endDate.substring(0, 4));
        int endMonth = 0;
        if(endDate.substring(4, 5).equals("0"))
            endMonth = Integer.parseInt(endDate.substring(5));
        endMonth = Integer.parseInt(endDate.substring(4, 6));
        int intervalMonth = (endYear * 12 + endMonth) - (startYear * 12 + startMonth);
        return intervalMonth;
    }

    public static String dateToString(Date date)
    {
        if(date == null)
        {
            return null;
        } else
        {
            String strDate = "";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            strDate = simpleDateFormat.format(date);
            return strDate;
        }
    }

    public static String datetimeToString(Date date)
    {
        if(date == null)
        {
            return null;
        } else
        {
            String strDate = "";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            strDate = simpleDateFormat.format(date);
            return strDate;
        }
    }

    public static String datetimeToString(Date date, String format)
    {
        if(date == null)
        {
            return null;
        } else
        {
            String strDate = "";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            strDate = simpleDateFormat.format(date);
            return strDate;
        }
    }

    public static String timeToString(Date date)
    {
        if(date == null)
        {
            return null;
        } else
        {
            String strDate = "";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
            strDate = simpleDateFormat.format(date);
            return strDate;
        }
    }

    public static Date stringToDate(String strDate, String srcDateFormat, String dstDateFormat)
    {
        Date rtDate = null;
        Date tmpDate = (new SimpleDateFormat(srcDateFormat)).parse(strDate, new ParsePosition(0));
        String tmpString = null;
        if(tmpDate != null)
            tmpString = (new SimpleDateFormat(dstDateFormat)).format(tmpDate);
        if(tmpString != null)
            rtDate = (new SimpleDateFormat(dstDateFormat)).parse(tmpString, new ParsePosition(0));
        return rtDate;
    }

    public static Date stringToDate(String strDate, String srcDateFormat)
    {
        return stringToDate(strDate, srcDateFormat, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date stringToDate(String strDate)
    {
        return stringToDate(strDate, "yyyy-MM-dd HH:mm:ss");
    }

    public static java.sql.Date utilDateToSqlDate(Date date)
    {
        if(date == null)
            return null;
        else
            return new java.sql.Date(date.getTime());
    }

    public static Time utilDateToSqlTime(Date date)
    {
        if(date == null)
            return null;
        else
            return new Time(date.getTime());
    }

    public static Timestamp utilDateToSqlTimestamp(Date date)
    {
        if(date == null)
            return null;
        else
            return new Timestamp(date.getTime());
    }

    public static java.sql.Date stringToSqlDate(String strDate)
    {
        return stringToSqlDate(strDate, "yyyy-MM-dd");
    }

    public static java.sql.Date stringToSqlDate(String strDate, String srcDateFormat)
    {
        return stringToSqlDate(strDate, srcDateFormat, "yyyy-MM-dd");
    }

    public static java.sql.Date stringToSqlDate(String strDate, String srcDateFormat, String dstDateFormat)
    {
        return utilDateToSqlDate(stringToDate(strDate, srcDateFormat, dstDateFormat));
    }

    public static Time stringToSqlTime(String strDate)
    {
        return stringToSqlTime(strDate, "HH:mm:ss");
    }

    public static Time stringToSqlTime(String strDate, String srcDateFormat)
    {
        return stringToSqlTime(strDate, srcDateFormat, "HH:mm:ss");
    }

    public static Time stringToSqlTime(String strDate, String srcDateFormat, String dstDateFormat)
    {
        return utilDateToSqlTime(stringToDate(strDate, srcDateFormat, dstDateFormat));
    }

    public static Timestamp stringToSqlTimestamp(String strDate)
    {
        return stringToSqlTimestamp(strDate, "yyyy-MM-dd HH:mm:ss");
    }

    public static Timestamp stringToSqlTimestamp(String strDate, String srcDateFormat)
    {
        return stringToSqlTimestamp(strDate, srcDateFormat, "yyyy-MM-dd HH:mm:ss");
    }

    public static Timestamp stringToSqlTimestamp(String strDate, String srcDateFormat, String dstDateFormat)
    {
        return utilDateToSqlTimestamp(stringToDate(strDate, srcDateFormat, dstDateFormat));
    }

    public static String toTimeString(int hour, int minute, int second)
    {
        String hourStr;
        if(hour < 10)
            hourStr = "0" + hour;
        else
            hourStr = String.valueOf(hour);
        String minuteStr;
        if(minute < 10)
            minuteStr = "0" + minute;
        else
            minuteStr = String.valueOf(minute);
        String secondStr;
        if(second < 10)
            secondStr = "0" + second;
        else
            secondStr = String.valueOf(second);
        if(second == 0)
            return hourStr + ":" + minuteStr;
        else
            return hourStr + ":" + minuteStr + ":" + secondStr;
    }

    public static java.sql.Date getDayStart(java.sql.Date date)
    {
        return getDayStart(date, 0);
    }

    public static java.sql.Date getDayStart(java.sql.Date date, int daysLater)
    {
        Calendar tempCal = Calendar.getInstance();
        tempCal.setTime(new Date(date.getTime()));
        tempCal.set(tempCal.get(1), tempCal.get(2), tempCal.get(5), 0, 0, 0);
        tempCal.add(5, daysLater);
        return new java.sql.Date(tempCal.getTime().getTime());
    }

    public static java.sql.Date getNextDayStart(java.sql.Date date)
    {
        return getDayStart(date, 1);
    }

    public static java.sql.Date getDayEnd(java.sql.Date stamp)
    {
        return getDayEnd(stamp, 0);
    }

    public static java.sql.Date getDayEnd(java.sql.Date stamp, int daysLater)
    {
        Calendar tempCal = Calendar.getInstance();
        tempCal.setTime(new Date(stamp.getTime()));
        tempCal.set(tempCal.get(1), tempCal.get(2), tempCal.get(5), 23, 59, 59);
        tempCal.add(5, daysLater);
        return new java.sql.Date(tempCal.getTime().getTime());
    }

    public static java.sql.Date monthBegin()
    {
        Calendar mth = Calendar.getInstance();
        mth.set(5, 1);
        mth.set(11, 0);
        mth.set(12, 0);
        mth.set(13, 0);
        mth.set(9, 0);
        return new java.sql.Date(mth.getTime().getTime());
    }

    public static String getDateTimeDisp(String datetime)
    {
        if(datetime == null || datetime.equals(""))
        {
            return "";
        } else
        {
            DateFormat formatter = DateFormat.getDateTimeInstance(2, 2);
            long datel = Long.parseLong(datetime);
            return formatter.format(new Date(datel));
        }
    }

    public static boolean isYear(String year)
    {
        if(year == null)
            return false;
        if(year.length() != 4)
            return false;
        return StringUtils.isNumeric(year);
    }
    /**
     * 判断字符是否是数字
     * @param str
     * @return
     */
    public boolean isNumeric(String str)
    {
           Pattern pattern = Pattern.compile("[0-9]*");
           Matcher isNum = pattern.matcher(str);
           if( !isNum.matches() ) {
              return false;
           }
           return true;
    }

    public static boolean isMonth(String month)
    {
        if(month == null)
            return false;
        if(month.length() != 1 && month.length() != 2)
            return false;
        if(!StringUtils.isNumeric(month))
            return false;
        int iMonth = Integer.parseInt(month);
        return iMonth >= 1 && iMonth <= 12;
    }

    public static boolean isDay(String day)
    {
        if(day == null)
            return false;
        if(day.length() != 1 && day.length() != 2)
            return false;
        if(!StringUtils.isNumeric(day))
            return false;
        int iDay = Integer.parseInt(day);
        return iDay >= 1 && iDay <= 31;
    }

    public static boolean isHour(String hour)
    {
        if(hour == null)
            return false;
        if(hour.length() != 1 && hour.length() != 2)
            return false;
        if(!StringUtils.isNumeric(hour))
            return false;
        int iHour = Integer.parseInt(hour);
        return iHour >= 0 && iHour <= 23;
    }

    public static boolean isMinute(String minute)
    {
        if(minute == null)
            return false;
        if(minute.length() != 1 && minute.length() != 2)
            return false;
        if(!StringUtils.isNumeric(minute))
            return false;
        int iMinute = Integer.parseInt(minute);
        return iMinute >= 0 && iMinute <= 59;
    }

    public static boolean isSecond(String second)
    {
        if(second == null)
            return false;
        if(second.length() != 1 && second.length() != 2)
            return false;
        if(!StringUtils.isNumeric(second))
            return false;
        int iSecond = Integer.parseInt(second);
        return iSecond >= 0 && iSecond <= 59;
    }

    public static boolean isDate(String year, String month, String day)
    {
        if(!isYear(year))
            return false;
        if(!isMonth(month))
            return false;
        if(!isDay(day))
        {
            return false;
        } else
        {
            int iYear = Integer.parseInt(year);
            int iMonth = Integer.parseInt(month);
            int iDay = Integer.parseInt(day);
            return verityDate(iYear, iMonth, iDay);
        }
    }

    public static boolean isDate(String date)
    {
        if(Utils.isEmpty(date))
            return false;
        char divide = '-';
        int index = date.indexOf(divide);
        if(index < 0)
            return false;
        String year = date.substring(0, index);
        int index2 = date.indexOf(divide, index + 1);
        if(index2 < 0)
        {
            return false;
        } else
        {
            String month = date.substring(index + 1, index2);
            String day = date.substring(index2 + 1);
            return isDate(year, month, day);
        }
    }
}
